package io.persimmon.springboot.trace;

import io.persimmon.core.module.trace.TraceContext;
import io.persimmon.core.module.trace.TraceManager;
import io.persimmon.springboot.trace.bo.TraceHandler;
import io.persimmon.springboot.trace.bo.TraceRequestContext;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Objects;

@Component
public class TraceInterceptor implements HandlerInterceptor {

    private static final String TRACE_HEADER = "x-trace";
    @Autowired(required = false)
    private TraceHandler traceHandler;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String traceName = request.getHeader(TRACE_HEADER);
        if (Objects.nonNull(traceHandler) && StringUtils.isNotEmpty(traceName)) {
            TraceManager.createTrace(traceName);
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        if (Objects.nonNull(traceHandler)) {
            List<TraceContext> traceContextList = TraceManager.currentTraces();
            if (!traceContextList.isEmpty()) {
                TraceContext traceContext = traceContextList.get(0);
                TraceRequestContext traceRequestContext = new TraceRequestContext(request, traceContext);
                traceHandler.handleRequest(traceRequestContext);
                TraceManager.removeTrace(traceContext);
            }
        }
        TraceManager.removeAllTrace();
    }
}
